﻿using System;
using System.Collections.Generic;
using System.Linq;
using oModbus.Utility;

namespace oModbus.Message
{
    public class WriteMultipleRegisterRequest : AbstractModbusMessage
    {
        public WriteMultipleRegisterRequest(byte slaveAddress, ushort startAddress, ushort outNumber, List<byte> valueS) : base(slaveAddress, FunctionCode.WriteMultipleRegister)
        {
            StartAddress = startAddress;
            RegisterNumber = outNumber;
            ValueS = valueS;
        }

        public WriteMultipleRegisterRequest(byte[] messageBytes) : base(messageBytes)
        {
        }
        /// <summary>
        /// 开始地址
        /// </summary>
        public ushort StartAddress { get; set; }
        /// <summary>
        /// 寄存器数量
        /// </summary>
        public ushort RegisterNumber { get; set; }
        /// <summary>
        /// 字节数 2×N*
        /// </summary>
        public byte ByteSize { get; private set; }

        private List<byte> _valueS;
        /// <summary>
        /// 值
        /// </summary>
        public List<byte> ValueS
        {
            get { return _valueS; }
            set
            {
                _valueS = value;
                ByteSize = (byte)_valueS.Count;
            }
        }
        protected override void Packing()
        {
            base.Packing();
            MessageData.AddRange(StartAddress.GetBytes());//开始地址
            MessageData.AddRange(RegisterNumber.GetBytes()); 
            MessageData.Add(ByteSize);
            MessageData.AddRange(ValueS);
            Crc = MessageData.ToArray().CalculateCrc();
        }

        public override bool Analysis(byte[] messageBytes)
        {
            if (messageBytes.Length >= 8)
            {
                MessageData = messageBytes.ToList();
                SlaveAddress = messageBytes[0];
                FunctionCode = (FunctionCode)Convert.ToInt32(messageBytes[1]);
                StartAddress = ConvertExtend.GetUint16(messageBytes[2], messageBytes[3]);
                RegisterNumber = ConvertExtend.GetUint16(messageBytes[4], messageBytes[5]);
                ByteSize = messageBytes[6];
                _valueS = new List<byte>();
                for (int i = 7; i < messageBytes.Length - 2; i++)
                {
                    _valueS.Add(messageBytes[i]);
                }
                Crc = new List<byte>() {
                    messageBytes[messageBytes.Length - 2],
                    messageBytes[messageBytes.Length - 1]
                }.ToArray();

                return true;
            }
            return false;
        }
    }
}
